{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 12.3 补充知识点：人脸识别外部接口调用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'error_code': 0, 'error_msg': 'SUCCESS', 'log_id': 510194001753, 'timestamp': 1577327914, 'cached': 0, 'result': {'face_num': 1, 'face_list': [{'face_token': 'e9715854c4425de80866a7a0fd256c4c', 'location': {'left': 1327.56, 'top': 1150.89, 'width': 1116, 'height': 1060, 'rotation': 0}, 'face_probability': 1, 'angle': {'yaw': -1.58, 'pitch': 9.21, 'roll': -1.13}, 'age': 25, 'gender': {'type': 'male', 'probability': 1}, 'beauty': 73.49}]}}\n",
      "年龄预测为：25\n",
      "性别预测为：male\n",
      "颜值评分为：73.49\n"
     ]
    }
   ],
   "source": [
    "from aip import AipFace\n",
    "import base64\n",
    "\n",
    "# 下面3行内容为自己的APP_ID,API_KEY,SECRET_KEY\n",
    "APP_ID = '16994639'\n",
    "API_KEY = 'L9XnkKQEMnHhB5omF2P8D9OM'\n",
    "SECRET_KEY = 'nnOZDoruZ6AjVglBs6ecvUjFRIAKrn9T'\n",
    "\n",
    "# 把上面输入的账号信息传入接口\n",
    "aipFace = AipFace(APP_ID, API_KEY, SECRET_KEY)\n",
    "\n",
    "# 下面一行内容为需要识别的人脸图片的地址，其他地方就不用改了\n",
    "filePath = r'王宇韬.jpg'\n",
    "\n",
    "# 定义打开文件的函数\n",
    "def get_file_content(filePath):\n",
    "    with open(filePath, 'rb') as fp:\n",
    "        content = base64.b64encode(fp.read())\n",
    "        return content.decode('utf-8')\n",
    "\n",
    "imageType = \"BASE64\"\n",
    "\n",
    "# 选择最后要展示的内容，这里展示age（年龄）；gender（性别）；beauty（颜值）\n",
    "options = {}\n",
    "options[\"face_field\"] = \"age,gender,beauty\"\n",
    "\n",
    "# 调用接口aipFace的detect()函数进行人脸识别，打印结果\n",
    "result = aipFace.detect(get_file_content(filePath), imageType, options)\n",
    "print(result)\n",
    "\n",
    "# 打印具体信息，本质就是列表索引和字典的键值对应\n",
    "age = result['result']['face_list'][0]['age']\n",
    "print('年龄预测为：' + str(age))\n",
    "gender = result['result']['face_list'][0]['gender']['type']\n",
    "print('性别预测为：' + gender)\n",
    "beauty = result['result']['face_list'][0]['beauty']\n",
    "print('颜值评分为：' + str(beauty))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
